//
//  SCPhotoAlbumPreviewViewController.m
//  PhotoAlbum
//
//  Created by Chao Sheng on 2021/12/4.
//

#import "SCPhotoAlbumPreviewViewController.h"
#import "SCPhotoPreviewViewCell.h"
#import "SCPhotoPreviewPresentAnimationTransition.h"

@interface SCPhotoAlbumPreviewViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>

@property (nonatomic, strong) UIView *titleView;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UILabel *subtitleLabel;

@end

@implementation SCPhotoAlbumPreviewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    if (@available(iOS 15, *)) {
        UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
        appearance.shadowColor = [UIColor clearColor];
        appearance.shadowImage = [SCPhotoTools imageLineWithColor:[UIColor colorWithWhite:0.8 alpha:0.5]];
        self.navigationController.navigationBar.scrollEdgeAppearance = appearance;// 带scroll滑动的页面
        self.navigationController.navigationBar.standardAppearance = appearance;// 常规页面
    }
    
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)setupUI {
    
    self.titleView.frame = CGRectMake(0, 0, 200, 44);
    self.titleLabel.frame = CGRectMake(0, 9, 200, 15);
    self.subtitleLabel.frame = CGRectMake(0, CGRectGetMaxY(self.titleLabel.frame)+4, 200, 12);
    self.navigationItem.titleView = self.titleView;
    
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.bottomView];
    
    self.bottomView.selectedArray = self.manager.selectedArray;
    self.bottomView.selectedIndex = self.selectedIndex;
    sc_weak(self);
    self.bottomView.scSrollPreview = ^(SCPhotoModel * _Nonnull model) {
        NSInteger index = [weakself.photoList indexOfObject:model];
        //NSLog(@"====%ld",index);
        weakself.currentModelIndex = index;
        [weakself.collectionView setContentOffset:CGPointMake(weakself.currentModelIndex *(sc_WIDTH+10), 0) animated:YES];
    };
    self.bottomView.scCompletion = ^{
        if (weakself.scCompletion) {
            weakself.scCompletion();
        }
        [weakself.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
//        SCPhotoModel *model = weakself.photoList[weakself.currentModelIndex];
//        if( ![weakself.manager.selectedArray containsObject:model]) {
//            [weakself.manager.selectedArray addObject:model];
//        }
//        if (weakself.manager.ocrEnable && [weakself neetOcrImageText]) {
//            [MBProgressHUD showSCLoadind:@"正在识别，请稍后..."];
//            [[SCHWCloudManager shareInstance] ocrImages:weakself.manager.selectedArray success:^{
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [MBProgressHUD hideSCHud];
//                    if (weakself.scCompletion) {
//                        weakself.scCompletion();
//                    }
//                    [weakself.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
//                });
//            } failure:^(NSError * _Nonnull error) {
//
//            }];
//        } else {
//            if (weakself.scCompletion) {
//                weakself.scCompletion();
//            }
//            [weakself.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
//        }

    };

    self.collectionView.contentSize = CGSizeMake(self.photoList.count * (sc_WIDTH+10), 0);
    [self.collectionView setContentOffset:CGPointMake(self.currentModelIndex *(sc_WIDTH+10), 0)];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 44, 44);
    [button setImage:[UIImage sc_bundleImageNamed:@"LGQ-photoback"] forState:UIControlStateNormal];
    [button setImage:[UIImage sc_bundleImageNamed:@"LGQ-photoback"] forState:UIControlStateHighlighted];
    [button setImageEdgeInsets:UIEdgeInsetsMake(6,-15,6,40)];
    [button addTarget:self action:@selector(didCancelClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}

- (SCPhotoPreviewViewCell *)currentPhotoCell:(SCPhotoModel *)model {
    if (!model || ![self.photoList containsObject:model]) {
        return nil;
    }
    
    SCPhotoPreviewViewCell *cell = (SCPhotoPreviewViewCell*)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentModelIndex inSection:0]];
    
    return cell;
}

- (void)didCancelClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

//判断是否需要识别图片中的文字
- (BOOL)neetOcrImageText {
    BOOL need = NO;
    for (SCPhotoModel *model in self.manager.selectedArray) {
        if(!model.ocrTextUsed) {
            need = YES;
            break;
        }
    }
    return need;
}

- (void)setOrigin:(NSInteger)origin {
    _origin = origin;
    self.bottomView.hiddenCompletion = _origin==0 ? false : true;
}

- (void)setCurrentModelIndex:(NSInteger)currentModelIndex {
    _currentModelIndex = currentModelIndex;
    SCPhotoModel *model = self.photoList[_currentModelIndex];
    self.titleLabel.text = [SCPhotoTools transFromYMDTime:model.date];
    self.subtitleLabel.text = [SCPhotoTools transFromMHTime:model.date];
}

#pragma mark - collectionView delegate & dataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.photoList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SCPhotoPreviewViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SCPhotoPreviewViewCell" forIndexPath:indexPath];
    cell.photoModel = self.photoList[indexPath.row];
    
    sc_weak(self);
    cell.scCellTapClick = ^{
        [weakself setSubviewAlphaAnimate:YES];
    };
    
    return cell;
}



- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView != self.collectionView) {
        return;
    }
    
    NSInteger currentIndex = self.collectionView.contentOffset.x / (sc_WIDTH + 10);
    if (currentIndex > self.photoList.count - 1) {
        currentIndex = self.photoList.count - 1;
    }
    if (currentIndex < 0) {
        currentIndex = 0;
    }
    
    SCPhotoModel *model = self.photoList[currentIndex];
    self.titleLabel.text = [SCPhotoTools transFromYMDTime:model.date];
    self.subtitleLabel.text = [SCPhotoTools transFromMHTime:model.date];
    
    self.currentModelIndex = currentIndex;
    
//    //更新bottom上缩略图的选中显示
//    self.bottomView.selectedIndex = model.selectedIndex;
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //更新bottom上缩略图的选中显示
    SCPhotoModel *model = self.photoList[self.currentModelIndex];
    self.bottomView.selectedIndex = model.selectedIndex;
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    //更新bottom上缩略图的选中显示
    SCPhotoModel *model = self.photoList[self.currentModelIndex];
    self.bottomView.selectedIndex = model.selectedIndex;
}

#pragma mark - action
// 导航栏和工具栏显示隐藏动画
- (void)setSubviewAlphaAnimate:(BOOL)animation {
    BOOL hide = NO;
    if (self.bottomView.alpha == 1) {
        hide = YES;
    }
    
    if (!hide) {
        [self.navigationController setNavigationBarHidden:hide animated:NO];
    }
    self.bottomView.userInteractionEnabled = !hide;
    
    if (animation) {
        [[UIApplication sharedApplication] setStatusBarHidden:hide withAnimation:UIStatusBarAnimationFade];
        [UIView animateWithDuration:0.15 animations:^{
            self.navigationController.navigationBar.alpha = hide ? 0 : 1;
            self.view.backgroundColor = hide ? [UIColor blackColor] : [UIColor whiteColor];
            self.collectionView.backgroundColor = hide ? [UIColor blackColor] : [UIColor whiteColor];
            self.bottomView.alpha = hide ? 0 : 1;
        } completion:^(BOOL finished) {
            if (hide) {
                [self.navigationController setNavigationBarHidden:hide animated:NO];
            }
        }];
    } else {
        [[UIApplication sharedApplication] setStatusBarHidden:hide];
        self.view.backgroundColor = hide ? [UIColor blackColor] : [UIColor whiteColor];
        self.collectionView.backgroundColor = hide ? [UIColor blackColor] : [UIColor whiteColor];
        self.bottomView.alpha = hide ? 0 : 1;
        if (hide) {
            [self.navigationController setNavigationBarHidden:hide];
        }
    }
}

#pragma mark - 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 0);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.itemSize = CGSizeMake(sc_WIDTH,sc_HEIGHT - sc_NAVIGATION_HEIGHT - sc_BOTTOMPADDING_HEIGHT);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(-10, 0,sc_WIDTH + 10, sc_HEIGHT - sc_BOTTOMPADDING_HEIGHT) collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[SCPhotoPreviewViewCell class] forCellWithReuseIdentifier:@"SCPhotoPreviewViewCell"];
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
            
    }
    return _collectionView;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[SCPreviewBottomView alloc] initWithFrame:CGRectMake(0, sc_HEIGHT-50-sc_BOTTOMPADDING_HEIGHT, sc_WIDTH, 50+sc_BOTTOMPADDING_HEIGHT)];
    }
    return _bottomView;
}

- (UIView *)titleView {
    if (!_titleView) {
        _titleView = [[UIView alloc] init];
        [_titleView addSubview:self.titleLabel];
        [_titleView addSubview:self.subtitleLabel];
    }
    return _titleView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

- (UILabel *)subtitleLabel {
    if (!_subtitleLabel) {
        _subtitleLabel = [[UILabel alloc] init];
        _subtitleLabel.textAlignment = NSTextAlignmentCenter;
        _subtitleLabel.textColor = [UIColor blackColor];
        _subtitleLabel.font = [UIFont systemFontOfSize:11];
    }
    return _subtitleLabel;;
}

- (void)dealloc {
    NSLog(@"预览释放");
}

@end
